package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;
    @Override
    public User WXlogin(String code) {
        //调用微信接口服务
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String s = HttpClientUtil.doGet(url, map);
        System.out.println(s);
        //判断用户id是否正确
        if (!s.isEmpty()){
            User user = JSON.parseObject(s, User.class);
            //判断用户是否是新用户
            User login = userMapper.login(user);
            if (login == null){
                System.out.println("新用户");
                //如果是新用户则创建用户信息
                user.setCreateTime(LocalDateTime.now());
                userMapper.register(user);
                return userMapper.login(user);
            }

            System.out.println("老用户");
            System.out.println(user);
            //如果是老用户则更新用户信息
            return login;
            //返回用户信息
        }
        throw  new LoginFailedException("登录失败");
    }
}
